package cn.sjtu.design_pattern.singleton;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author syo 2319615164@qq.com
 * @description CAS方式实现单例
 * @date 2024/5/16
 * @Copyright syo
 */
public class Singleton05 {
    // 1. CAS原子引用
    private static final AtomicReference<Singleton05> INSTANCE = new AtomicReference<Singleton05>();

    // 2. 私有化构造函数
    private Singleton05() {}

    // 3. 获取单例的方法
    public static Singleton05 getInstance() {
        for (;;) {
            Singleton05 instance = INSTANCE.get();
            if (instance != null) {
                return instance;
            }

            instance = new Singleton05();
            if (INSTANCE.compareAndSet(null, instance)) {
                return instance;
            }
        }
    }
}
